package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RequestMappingHandlerMapping rmhm;

    @Override
    public void reload() {
        //1.一次性把所有的权限信息查出来
        List<Permission> permissions = permissionMapper.selectAll();
        Set<String> expressionSet = new HashSet<>();
        for (Permission p : permissions) {
            expressionSet.add(p.getExpression());
        }
        //获取到所有贴了RequiredPermission注解，取出注解上的name 和expression,封装成Permission。保存到数据库中
        //handlerMethods代表了每一个方法的引用
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
        Collection<HandlerMethod> values = handlerMethods.values();
        //判断
        for (HandlerMethod method : values) {
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            if (methodAnnotation!=null){  //说明方法上贴了注解
                String expression = methodAnnotation.expression();
                if (!expressionSet.contains(expression)){
                    //目前扫描到的表达式不在集合中
                    Permission p = new Permission();
                    p.setName(methodAnnotation.name());
                    p.setExpression(expression);
                    permissionMapper.insert(p);
                }else{
                    //目前扫描到的表达式在集合中
                    expressionSet.remove(expression);
                }
            }
        }

        //如果expressionSet不为空，说明有些权限已经删除了，代码中已经没有了，但是数据库中依然存在，根据表达式删除权限
        for (String expression : expressionSet) {
            permissionMapper.deleteByExpression(expression);
        }
    }

    @Override
    public PageInfo selectList(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List list= permissionMapper.selectList(qo);
        return new PageInfo(list);
    }

    @Override
    public List selectAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public List selectByRoleId(Long roleId) {
        return permissionMapper.selectByRoleId(roleId);
    }

    @Override
    public List<Permission> selectByEmpId(Long empId) {
        return permissionMapper.selectByEmpId(empId);
    }
}
